package com.example.demo.shiro;

import com.example.demo.model.User;
import com.example.demo.service.UserService;
import com.example.demo.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author Eric Wu
 * @since 1.8
 * create 2020-06-09
 */
@Service
@Slf4j
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private JWTUtil jwtUtil;

    @Override
    public boolean supports(AuthenticationToken token) {
        return super.supports(token);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        String userName = jwtUtil.getUserName(principals.toString());
        User user = userService.queryUserByName(userName).get();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole(String.valueOf(user.getRoleId()));
        simpleAuthorizationInfo.addStringPermission("all");
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken auth) throws AuthenticationException {
        String token = (String)auth.getCredentials();
        String userName = jwtUtil.getUserName(token);
        if(StringUtils.hasText(userName)){
            throw new AuthenticationException("token invalid");
        }
        User user = userService.queryUserByName(userName).get();
        if(user == null){
            throw new AuthenticationException("User didn't exited!");
        }
        if(! jwtUtil.verify(token,userName,user.getPassword())){
            throw new AuthenticationException("Username or password error");
        }
        return new SimpleAuthenticationInfo(token,token,"my_realm");
    }
}
